package com.handpay.zztong.hp.main.activity;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.text.TextUtils;
import android.view.Menu;
import android.view.View;
import android.view.WindowManager;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.RelativeLayout;

import com.handpay.framework.ClientEngine;
import com.handpay.framework.SecureManager;
import com.handpay.framework.notice.ApiNoticeFactory;
import com.handpay.framework.notice.ApiNoticeListener;
import com.handpay.framework.swiper.landi.AipSharedPreferences;
import com.handpay.framework.utils.CommonUtils;
import com.handpay.framework.utils.UserCheckTimeout;
import com.handpay.zztong.hp.R;
import com.handpay.zztong.hp.ZZTApplication;
import com.handpay.zztong.hp.base.activity.ZZTongActivity;
import com.handpay.zztong.hp.base.callback.BusinessEngineListener;
import com.handpay.zztong.hp.base.fragment.BaseFragment;
import com.handpay.zztong.hp.base.service.CoreService;
import com.handpay.zztong.hp.config.ZZTConfig;
import com.handpay.zztong.hp.config.ZZTConstant;
import com.handpay.zztong.hp.db.ormlite.DataBaseComponentModel;
import com.handpay.zztong.hp.db.ormlite.DataBaseModel;
import com.handpay.zztong.hp.jpush.JpushManager;
import com.handpay.zztong.hp.log.HPLog;
import com.handpay.zztong.hp.login.activity.ModifyLoginPwdActivity;
import com.handpay.zztong.hp.login.model.verifyversion.VerifyVersionBean;
import com.handpay.zztong.hp.login.model.verifyversion.VerifyVersionModel;
import com.handpay.zztong.hp.main.model.component.ComponentHttpBean;
import com.handpay.zztong.hp.main.model.component.ComponentItemBean;
import com.handpay.zztong.hp.main.model.component.ComponentMappingItemBean;
import com.handpay.zztong.hp.main.model.component.ComponentRelationItemBean;
import com.handpay.zztong.hp.main.model.component.CustomComponentModel;
import com.handpay.zztong.hp.main.model.merchantcollect.MerchantCollectModel;
import com.handpay.zztong.hp.protocol.ATProtocolConstant;
import com.handpay.zztong.hp.protocol.BaseProtocolKey;
import com.handpay.zztong.hp.utils.AccountUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Hashtable;
import java.util.List;

@SuppressLint("NewApi")
public class MainActivity extends ZZTongActivity implements OnCheckedChangeListener, ApiNoticeListener {
    // 标题栏
    private FragmentManager fragmentManager = null;
    private FragmentTransaction fragmentTransaction = null;
    private BaseFragment myFragment = null;
    public static String currFragTag = "";
    private RadioGroup radio_group;
    private RadioButton radio_home, radio_receivables,radio_my;
    private View roundView;
    public static boolean isReceivablesFragment = false;
    public boolean isFirstOpen = false;
    private JpushManager jpushManager;
    public static boolean isForeground;
    private VerifyVersionModel mVerifyVersionModel;
    private MerchantCollectModel mMerchantCollectModel;
    //当前是否已经显示用户协议弹框
    private boolean currentShowAgreement = false;
    private ServiceConnection mCoreServiceConn = new ServiceConnection() {
        /** 获取服务对象时的操作 */
        public void onServiceConnected(ComponentName name, IBinder service) {
        }

        /** 无法获取到服务对象时的操作 */
        public void onServiceDisconnected(ComponentName name) {

        }

    };

    public BaseFragment getCurrentFragment() {
        return myFragment;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        mMerchantCollectModel = new MerchantCollectModel();
        mVerifyVersionModel = new VerifyVersionModel();

        setContentView(R.layout.activity_main);
        super.onCreate(savedInstanceState);
        Intent getIntent = getIntent();
        mIsMainPage = true;
        initUI();
        fragmentManager = getFragmentManager();
        setDefaultFirstFragment(ZZTConstant.BTN_FLAG_HOME);
        ((ZZTApplication) getApplication()).setMainActivity(this);
        Intent service = new Intent(MainActivity.this, CoreService.class);
        this.bindService(service, mCoreServiceConn, Context.BIND_AUTO_CREATE);
        if (getIntent != null && getIntent.getBooleanExtra("isComposeIntent", false)) {
            startActivity(getComposeIntent());
        }
        submitCountdata();
        startDefaultFragment(getIntent);
        ApiNoticeFactory.getInstance().registerApiNoticeListener(this);
        //-----------------------------极光推送相关配置start--------------------
        if (!TextUtils.isEmpty(AccountUtils.getUserId(this))) {
            jpushManager = new JpushManager(this);
            jpushManager.setAlias(AccountUtils.getUserId(this));
            jpushManager.setStyleBasic();
        }
        //-----------------------------极光推送相关配置end--------------------
        doCustomComponentList();
    }

    @Override
    protected void onStart() {
        super.onStart();
        //登入状态，未同意过，当前未显示(解决黑屏在开屏情况)
        if (isLogin() && !isAgreeMented() && !currentShowAgreement) {
            showAgreement();
        }
    }

    @Override
    public void setStatusBar() {

    }

    // new add code
    private void submitCountdata() {
        Hashtable<String, String> params = new Hashtable<String, String>();
        params.put("platform", "Android");
        params.put("tudid", ClientEngine.getInstance().getDeviceUuid());
        params.put("channel", ZZTConfig.CHANNEL);
        params.put("clientChannel", ZZTConfig.UPDATE_CHANNEL);
        params.put("clientVersion", ClientEngine.VERSION);
        mMerchantCollectModel = new MerchantCollectModel();
        mMerchantCollectModel.doMerchantCollectPost(this, params, null);
    }

    public static String stampToDate(long lt) {
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date(lt);
        res = simpleDateFormat.format(date);
        return res;
    }

    private void doCustomComponentList() {
       int POLL_TIME = CommonUtils.objectToInt(ClientEngine.getInstance().getGlobal(ZZTongActivity.POLL_TIME, 60 * 10));
        DataBaseComponentModel dbModel = new DataBaseComponentModel(getApplicationContext());
        List<ComponentItemBean> listbean = dbModel.queryComponentList();
        String updateTime = "0";
        if (listbean != null) {
            ComponentItemBean bean = dbModel.queryComponentList().get(0);
            if (bean != null) {
                updateTime = bean.getUpdateTime();
            }
        }
        HPLog.i(HPLog.YL_TAG, "组件间隔时间：" + POLL_TIME);
        HPLog.i(HPLog.YL_TAG, "组件当前时间：" + System.currentTimeMillis() + ":" + stampToDate(System.currentTimeMillis()));
        HPLog.i(HPLog.YL_TAG, "组件最后入库时间：" + updateTime + ":" + stampToDate(Long.valueOf(updateTime).longValue()));
        HPLog.i(HPLog.YL_TAG, "组件需要更新时间：" + (Long.valueOf(updateTime).longValue() + (POLL_TIME * 60 * 1000)) + ":" + stampToDate(Long.valueOf(updateTime).longValue() + (POLL_TIME * 60 * 1000)));

        if (Long.valueOf(updateTime) == 0 || System.currentTimeMillis() > (Long.valueOf(updateTime).longValue() + (POLL_TIME * 60 * 1000))) {
            Hashtable<String, String> params = new Hashtable<String, String>();
            params.put(BaseProtocolKey.CHANNEL, ClientEngine.CHANNEL);
            params.put(ATProtocolConstant.CLIENTCHANNEL, ZZTConfig.UPDATE_CHANNEL);

            new CustomComponentModel().doCustomComponentPost(MainActivity.this, params, new BusinessEngineListener<ComponentHttpBean>() {
                @Override
                public void callbackBusinessResponse(ComponentHttpBean httpBean) {
                    DataBaseComponentModel model = new DataBaseComponentModel(MainActivity.this);
                    List<ComponentHttpBean.ListBeanX> listX = httpBean.getList();
                    if (listX.size() == 0) {
                        return;
                    }
                    boolean bDelShowArea1 = false;
                    boolean bDelShowArea2 = false;
                    boolean bDelShowArea3 = false;
                    for (ComponentHttpBean.ListBeanX beanX : listX) {
                        String iconName = SecureManager.getInstance().des(beanX.getIconName(), 0, null);
                        String itemCode = SecureManager.getInstance().des(beanX.getItemCode(), 0, null);
                        String itemTitle = SecureManager.getInstance().des(beanX.getItemTitle(), 0, null);
                        String itemUrl = SecureManager.getInstance().des(beanX.getItemUrl(), 0, null);
                        String itemType = String.valueOf(beanX.getItemType());
                        int orderNum = beanX.getOrderNum();
                        String parentId = String.valueOf(beanX.getParentId());
                        String showArea = String.valueOf(beanX.getShowArea());
                        String updateTime = String.valueOf(System.currentTimeMillis());
                        ComponentMappingItemBean componentMappingItemBean = new ComponentMappingItemBean();
                        if (bDelShowArea1 == false && showArea.equals("1")) {
                            bDelShowArea1 = true;
                            model.deleteComponentMappingByShowArea("1");
                        }
                        if (bDelShowArea2 == false && showArea.equals("2")) {
                            bDelShowArea2 = true;
                            model.deleteComponentMappingByShowArea("2");
                        }
                        if (bDelShowArea3 == false && showArea.equals("3")) {
                            bDelShowArea3 = true;
                            model.deleteComponentMappingByShowArea("3");
                        }
                        if (itemType.equals("2")) {
                            model.deleteComponentRelationByParentId(itemCode);
                        }
                        componentMappingItemBean.setOrderNum(orderNum);
                        componentMappingItemBean.setItemCode(itemCode);
                        componentMappingItemBean.setShowArea(showArea);
                        componentMappingItemBean.setUpdateTime(updateTime);
                        model.addComponentMapping(componentMappingItemBean);
                        ComponentItemBean componentItemBean = new ComponentItemBean();
                        componentItemBean.setItemCode(itemCode);
                        componentItemBean.setItemTitle(itemTitle);
                        componentItemBean.setItemUrl(itemUrl);
                        componentItemBean.setItemType(itemType);
                        componentItemBean.setIconName(iconName);
                        componentItemBean.setUpdateTime(updateTime);
                        model.addComponent(componentItemBean);
                        List<ComponentHttpBean.ListBeanX.ListBean> list = beanX.getList();
                        for (ComponentHttpBean.ListBeanX.ListBean bean : list) {
                            String sIconName = SecureManager.getInstance().des(bean.getIconName(), 0, null);
                            String sItemCode = SecureManager.getInstance().des(bean.getItemCode(), 0, null);
                            String sItemTitle = SecureManager.getInstance().des(bean.getItemTitle(), 0, null);
                            String sItemUrl = SecureManager.getInstance().des(bean.getItemUrl(), 0, null);
                            String sItemType = String.valueOf(bean.getItemType());
                            int iOrderNum = bean.getOrderNum();
                            ComponentRelationItemBean componentRelationItemBean = new ComponentRelationItemBean();
                            componentRelationItemBean.setItemCode(sItemCode);
                            componentRelationItemBean.setOrderNum(iOrderNum);
                            componentRelationItemBean.setParentItemCode(itemCode);
                            model.addComponentRelation(componentRelationItemBean);
                            ComponentItemBean subComponentItemBean = new ComponentItemBean();
                            subComponentItemBean.setItemCode(sItemCode);
                            subComponentItemBean.setItemTitle(sItemTitle);
                            subComponentItemBean.setItemUrl(sItemUrl);
                            subComponentItemBean.setItemType(sItemType);
                            subComponentItemBean.setIconName(sIconName);
                            subComponentItemBean.setUpdateTime(updateTime);
                            model.addComponent(subComponentItemBean);
                        }
                    }
                    ApiNoticeFactory.getInstance().doBroadCastNotice(REFRESH_COMPONENT_ACTION, null);
                }
            });
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (isLogin()) {
            if (AccountUtils.getUserPasswordStatus(this) != 0 && flag_isShow_updatePWD) {
                //密码过期
//				showPasswordOutOfDate(AccountUtils.getUserPasswordStatus());
            }
        }
        isForeground = true;
    }

    private boolean isLogin() {
        if (TextUtils.isEmpty(AccountUtils.getAccountName(this))) {
            return false;
        }
        return true;
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (intent != null) {
            startDefaultFragment(intent);
        }
    }

    public void startDefaultFragment(Intent intent) {
        if (TextUtils.isEmpty(intent.getStringExtra(FRAGMENTFLAG))) {
            return;
        }
        if (!isFirstOpen) {
            isReceivablesFragment = true;
            removeMyFragment();
        }
        isFirstOpen = false;
        getDefaultFragment(intent.getStringExtra(FRAGMENTFLAG));
    }

    private void removeMyFragment() {
        fragmentTransaction = fragmentManager.beginTransaction();
        if (fragmentTransaction != null) {
            fragmentTransaction.remove(getFragment(ZZTConstant.FRAGMENT_FLAG_MY));
            fragmentTransaction.commit();
            fragmentTransaction = null;
        }
        hideNoticeRoundView();
    }

    public void getDefaultFragment(String tag) {
        if (!TextUtils.isEmpty(tag)) {
            if (ZZTConstant.FRAGMENT_FLAG_RECEIVABLES.equals(tag)) {
                radio_receivables.setChecked(true);
            } else if (ZZTConstant.FRAGMENT_FLAG_HOME.equals(tag)) {
                radio_home.setChecked(true);
            }else if (ZZTConstant.FRAGMENT_FLAG_MY.equals(tag)) {
                radio_my.setChecked(true);
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ApiNoticeFactory.getInstance().unregisterApiNoticeListener(this);
        unbindService(mCoreServiceConn);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    private void initUI() {
        roundView = findViewById(R.id.main_round);
        radio_group = (RadioGroup) findViewById(R.id.bottom_layout);
        radio_home = (RadioButton) findViewById(R.id.tab_main_home);
        radio_receivables = (RadioButton) findViewById(R.id.tab_main_shoukuan);
        radio_my  = (RadioButton) findViewById(R.id.tab_main_my);
        radio_group.setOnCheckedChangeListener(this);
//        initTabHeight();
    }


    public void switchPage(int positon) {
        String tag = "";
        switch (positon) {
            case ZZTConstant.BTN_FLAG_HOME:
                tag = ZZTConstant.FRAGMENT_FLAG_HOME;
                break;
            case ZZTConstant.BTN_FLAG_RECEIVABLES:
                tag = ZZTConstant.FRAGMENT_FLAG_RECEIVABLES;
                radio_receivables.setChecked(true);
                break;
            case ZZTConstant.BTN_FLAG_MY:
                tag = ZZTConstant.FRAGMENT_FLAG_MY;
                break;
            case ZZTConstant.BTN_FLAG_NEWS:
                tag = ZZTConstant.FRAGMENT_FLAG_DISCOVERY;
                break;
            default:
                tag = ZZTConstant.FRAGMENT_FLAG_HOME;
                break;
        }
        setTabSelection(tag);
    }

    private void setDefaultFirstFragment(int positon) {
        switchPage(positon);
        radio_home.setChecked(true);
    }

    private void commitTransactions(String tag) {
        if (fragmentTransaction != null && !fragmentTransaction.isEmpty()) {
            fragmentTransaction.commit();
            currFragTag = tag;
            fragmentTransaction = null;
            reFreshFragmentData();
        }
    }

    private void reFreshFragmentData() {
        if (myFragment != null && myActionBar != null) {
            myActionBar.refreshActionBar(myFragment.getFragmentActionBar());
        }
    }


    private FragmentTransaction ensureTransaction() {
        if (fragmentTransaction == null) {
            fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
        }
        return fragmentTransaction;

    }

    private void attachFragment(int layout, Fragment f, String tag) {
        if (f != null) {
            if (f.isDetached()) {
                ensureTransaction();
                fragmentTransaction.attach(f);

            } else if (!f.isAdded()) {
                ensureTransaction();
                fragmentTransaction.add(layout, f, tag);
            }
        }
    }

    private Fragment getFragment(String tag) {
        Fragment fragment = fragmentManager.findFragmentByTag(tag);
        if (fragment == null) {
            fragment = BaseFragment.newInstance(getApplicationContext(), tag);
        }
        return fragment;
    }

    private void detachFragment(Fragment f) {
        if (f != null && !f.isDetached()) {
            ensureTransaction();
            fragmentTransaction.detach(f);
        }
    }

    private void switchFragment(String tag) {
        if (TextUtils.equals(tag, currFragTag)) {
            return;
        }
        if (currFragTag != null && !currFragTag.equals("")) {
            detachFragment(getFragment(currFragTag));
        }
        myFragment = (BaseFragment) getFragment(tag);
        attachFragment(R.id.fragment_content, myFragment, tag);
        commitTransactions(tag);
    }

    public void setTabSelection(String tag) {
        fragmentTransaction = fragmentManager.beginTransaction();
        switchFragment(tag);
    }

    @Override
    protected void onStop() {
        super.onStop();
        currFragTag = "";
        isForeground = false;
//        jpushManager.stopJpush();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
    }

    /**
     * 根据checkedId来判断选定的Radio，从而进行页面的换
     */
    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        if (chekUserTimeout != null && chekUserTimeout.isTimeOut()) {
            showAlertDialog(this, getString(R.string.time_out_title), getString(R.string.time_out), false, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    exitAccount();
                    dialog.dismiss();
                }
            });
            return;
        }
        if (checkedId == R.id.tab_main_home) {
            switchPage(ZZTConstant.BTN_FLAG_HOME);
        } else if (checkedId == R.id.tab_main_shoukuan) {
            switchPage(ZZTConstant.BTN_FLAG_RECEIVABLES);
        } else if (checkedId == R.id.tab_main_my) {
            switchPage(ZZTConstant.BTN_FLAG_MY);
        } else if (checkedId == R.id.tab_main_news) {
            switchPage(ZZTConstant.BTN_FLAG_NEWS);
        } else {
            switchPage(ZZTConstant.BTN_FLAG_HOME);
        }
    }

    //    @Override
//    public boolean netJsonResponse(String action, ResponseBean resp, boolean showAlert) {
//        boolean bResult = super.netJsonResponse(action, resp, showAlert, new DialogInterface.OnClickListener() {
//            @Override
//            public void onClick(DialogInterface dialog, int which) {
//                dialog.dismiss();//在MainActivity界面捕获到服务器错误信息当前界面不关闭
//            }
//        });
//        return bResult || null == myFragment || myFragment.netJsonResponse(action, resp, showAlert, null);
//    }
//    @Override
//    public boolean netJsonResponse(String action, ResponseBean resp, boolean showAlert) {
//        boolean bResult = super.netJsonResponse(action, resp, showAlert, new DialogInterface.OnClickListener() {
//            @Override
//            public void onClick(DialogInterface dialog, int which) {
//                dialog.dismiss();//在MainActivity界面捕获到服务器错误信息当前界面不关闭
//            }
//        });
//        if (bResult) {
//            return bResult;
//        }
//        if (HttpUrlConstant.Do_CustomComponentList.equals(action)) {
//            ComponentHttpBean httpBean = (ComponentHttpBean) resp;
//            DataBaseComponentModel model = new DataBaseComponentModel(this);
//            List<ComponentHttpBean.ListBeanX> listX = httpBean.getList();
//            if (listX.size() == 0) {
//                return true;
//            }
//
//            boolean bDelShowArea1 = false;
//            boolean bDelShowArea2 = false;
//            boolean bDelShowArea3 = false;
//
//
//            for (ComponentHttpBean.ListBeanX beanX : listX) {
//                String iconName = SecureManager.getInstance().des(beanX.getIconName(), 0, null);
//                String itemCode = SecureManager.getInstance().des(beanX.getItemCode(), 0, null);
//                String itemTitle = SecureManager.getInstance().des(beanX.getItemTitle(), 0, null);
//                String itemUrl = SecureManager.getInstance().des(beanX.getItemUrl(), 0, null);
//                String itemType = String.valueOf(beanX.getItemType());
//                String orderNum = String.valueOf(beanX.getOrderNum());
//                String parentId = String.valueOf(beanX.getParentId());
//                String showArea = String.valueOf(beanX.getShowArea());
//                String updateTime = String.valueOf(System.currentTimeMillis());
//
//                ComponentMappingItemBean componentMappingItemBean = new ComponentMappingItemBean();
//                if (bDelShowArea1 == false && showArea.equals("1")) {
//                    bDelShowArea1 = true;
//                    model.deleteComponentMappingByShowArea("1");
//                }
//                if (bDelShowArea2 == false && showArea.equals("2")) {
//                    bDelShowArea2 = true;
//                    model.deleteComponentMappingByShowArea("2");
//                }
//                if (bDelShowArea3 == false && showArea.equals("3")) {
//                    bDelShowArea3 = true;
//                    model.deleteComponentMappingByShowArea("3");
//                }
//                componentMappingItemBean.setOrderNum(orderNum);
//                componentMappingItemBean.setItemCode(itemCode);
//                componentMappingItemBean.setShowArea(showArea);
//                componentMappingItemBean.setUpdateTime(updateTime);
//                model.addComponentMapping(componentMappingItemBean);
//
//                ComponentItemBean componentItemBean = new ComponentItemBean();
//                componentItemBean.setItemCode(itemCode);
//                componentItemBean.setItemTitle(itemTitle);
//                componentItemBean.setItemUrl(itemUrl);
//                componentItemBean.setItemType(itemType);
//                componentItemBean.setIconName(iconName);
//                componentItemBean.setUpdateTime(updateTime);
//
//                if (model.queryComponent(componentItemBean) == null) {
//                    model.addComponent(componentItemBean);
//                }
//
//                List<ComponentHttpBean.ListBeanX.ListBean> list = beanX.getList();
//                for (ComponentHttpBean.ListBeanX.ListBean bean : list) {
//                    String sIconName = SecureManager.getInstance().des(bean.getIconName(), 0, null);
//                    String sItemCode = SecureManager.getInstance().des(bean.getItemCode(), 0, null);
//                    String sItemTitle = SecureManager.getInstance().des(bean.getItemTitle(), 0, null);
//                    String sItemUrl = SecureManager.getInstance().des(bean.getItemUrl(), 0, null);
//
//                    String sItemType = String.valueOf(bean.getItemType());
//                    String sOrderNum = String.valueOf(bean.getOrderNum());
//
//                    ComponentRelationItemBean componentRelationItemBean = new ComponentRelationItemBean();
//                    componentRelationItemBean.setItemCode(sItemCode);
//                    componentRelationItemBean.setOrderNum(sOrderNum);
//                    componentRelationItemBean.setParentItemCode(itemCode);
//                    model.addComponentRelation(componentRelationItemBean);
//
//
//                    ComponentItemBean subComponentItemBean = new ComponentItemBean();
//                    subComponentItemBean.setItemCode(sItemCode);
//                    subComponentItemBean.setItemTitle(sItemTitle);
//                    subComponentItemBean.setItemUrl(sItemUrl);
//                    subComponentItemBean.setItemType(sItemType);
//                    subComponentItemBean.setIconName(sIconName);
//                    subComponentItemBean.setUpdateTime(updateTime);
//                    if (model.queryComponent(subComponentItemBean) == null) {
//                        model.addComponent(subComponentItemBean);
//                    }
//                }
//            }
//            ApiNoticeFactory.getInstance().doBroadCastNotice(REFRESH_COMPONENT_ACTION, null);
//        }
//        return bResult || null == myFragment || myFragment.netJsonResponse(action, resp, showAlert, null);
//    }

//    @Override
//    public boolean netResponse(String action, Hashtable<String, Object> resp, boolean showAlert) {
//        this.closeProgressDialog();
//        if (!action.equals(ZZTongActivity.Do_ZztAutoPaymentFinancingProduct) && !action.equals(ZZTongActivity.Do_GetUserNotices)  && !action.equals(ZZTongActivity.Do_GetPhotoSwitch) && !action.equals(ZZTongActivity.Do_getMerchantSwitch)) {
//            if (super.netResponse(action, resp, showAlert)) {
//                return true;
//            }
//        }
//        if (ZZTongActivity.Do_ZztGFFundIndex.equals(action)) {
//            byte data[] = (byte[]) resp.get(HttpEngine.Key_RespData);
//            LuaTable luaTable = LuaTableUtil.stringToLuaTable(data, isDataCompile);
//            String responseCode = (String) luaTable.rawget("responseCode");
//            String errorMessage = (String) luaTable.rawget("errMessage");
//            LuaTable chartsTable = (LuaTable) luaTable.rawget("charts");
//            if (errorMessage == null && responseCode == null && chartsTable != null) {
//                Intent intent = new Intent(MainActivity.this, GfFoundIndex.class);
//                intent.putExtra("indexData", data);
//                startActivity(intent);
//                // goBack();
//            } else {
//                DialogFactory.showAlertDialog(MainActivity.this, getString(R.string.tip), errorMessage != null ? errorMessage : getString(R.string.guangfa_system_error), true);
//            }
//        }
//        if (myFragment == null) {
//            return true;
//        }
//        return myFragment.netResponse(action, resp, showAlert, null, isDataCompile);
//    }

    @Override
    protected boolean isShownTabs() {
        return false;
    }

    @Override
    protected boolean isShownTopBar() {
        return false;
    }

    public void showNoticeRoundView() {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
//                if (myFragment != null) {
//                    myFragment.refreshRoundView();
//                }

                String userId = AccountUtils.getUserId(MainActivity.this);
                DataBaseModel dataBaseModel = DataBaseModel.getInstance(MainActivity.this);
                if (dataBaseModel.isReadNotice(userId)) {
                    roundView.setVisibility(View.VISIBLE);
                } else {
                    roundView.setVisibility(View.INVISIBLE);
                }
            }
        });
    }


    public void hideNoticeRoundView() {
        this.runOnUiThread(new Runnable() {

            @Override
            public void run() {
                roundView.setVisibility(View.INVISIBLE);
            }
        });
    }

//

    @Override
    public void goToVPos() {
        // super.goToVPos();
        HPLog.i("ConnectSwiperActivity", "--连接成功---goToVPos");
        myFragment.onVPOS();
    }

    @Override
    public void onNotifyNotice(int action, Bundle bundle) {
        HPLog.i(HPLog.YL_TAG, "Manactivity onNotifyNotice Action:" + action + " Bundle:" + bundle);
        if (action == NOTICE_ACTION) {
            showNoticeRoundView();
        } else if (action == VERIFY_UPDATE_ACTION) {
            if (AipSharedPreferences.getInstance(this).getVerifyLastTime() != -1) {
                long lastTime = AipSharedPreferences.getInstance(this).getVerifyLastTime();
                long currentTimeMillis = System.currentTimeMillis();
                if (currentTimeMillis - lastTime > UserCheckTimeout.TIME_HOUR) {
                    HPLog.i(HPLog.YL_TAG, "verify check:" + (currentTimeMillis - lastTime));
                    this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mVerifyVersionModel.doVerifyVersionPost(MainActivity.this,  new BusinessEngineListener<VerifyVersionBean>() {
                                @Override
                                public void callbackBusinessResponse(VerifyVersionBean bean) {
                                    doVerifyVersionCallback(bean);
                                }
                            });
                        }
                    });
                } else {
                    HPLog.i(HPLog.YL_TAG, "not verify check:" + (currentTimeMillis - lastTime));
                }
            }
        } else if (action == SWITCH_RECEIVABLES_ACTION) {
            switchPage(ZZTConstant.BTN_FLAG_RECEIVABLES);
        } else if (action == CUSTOM_COMPONENT_ACTION) {
            doCustomComponentList();
        }
    }

    public void doVerifyVersionCallback(VerifyVersionBean bean) {
        if (null != bean.getDgTrade()) {
            if ("0".equals(bean.getDgTrade())) {
                ZZTConfig.DW_TRADE = false;
            } else if ("1".equals(bean.getDgTrade())) {
                ZZTConfig.DW_TRADE = true;
            }
        }
        ClientEngine.getInstance().saveGlobal(POLL_TIME, bean.getPollTime());
        String version = bean.getVersion();
        String url = bean.getUrl();
        String description = bean.getDescription();
        String forcedUpdate = bean.getForcedUpdate();
        ClientEngine.getInstance().saveGlobal(VERSION, version);
        ClientEngine.getInstance().saveGlobal(DESCRIPTION, description);
        ClientEngine.getInstance().saveGlobal(UPDATEURL, url);
        ClientEngine.getInstance().saveGlobal(FORCEDUPDATE, forcedUpdate);
        HPLog.i("jjyang", "version:" + version + " url:" + url + " description:" + description + " forcedUpdate:" + forcedUpdate);
        if (TextUtils.isEmpty(url) && TextUtils.isEmpty(description)) {
            return;
        } else {
            description = description.replace("&", "\n");
        }
        String title = getString(R.string.updatetitle, version);
        String message = description;
        int result = version.compareTo(ClientEngine.VERSION);
        if ("0".equals(forcedUpdate) && result > 0) {
            String mVersion = null;
            mVersion = AipSharedPreferences.getInstance(this).getVersion();
            HPLog.i("ZZTongActivity", "mVersion:" + mVersion);
            if (!TextUtils.isEmpty(mVersion) && version.equals(mVersion)) {
                return;
            } else {
                isforcedCheckVersion(this, title, message, url, version);
            }
        } else {
            checkVersion(this, title, message, url);
        }
    }

    /**
     * 版本检测处理流程
     *
     * @param activity
     * @param title
     * @param message
     * @param url
     * @param version
     */
    public void isforcedCheckVersion(final ZZTongActivity activity, String title, String message, final String url, final String version) {
        showAlertDialog(activity, title, message, false, getResources().getString(R.string.immediately_update), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                try {
                    goToDownloadActivity(activity, url);
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
            }
        }, getResources().getString(R.string.not_update), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 暂时不更新，但用户可以进入应用，并使用功能
                dialog.dismiss();
                long currentTimeMillis = System.currentTimeMillis();
                AipSharedPreferences.getInstance(MainActivity.this).setVerifyLastTime(currentTimeMillis);

            }
        }, getResources().getString(R.string.no_longer_remind), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int arg1) {
                // 用户同样可以进入应用，但是，下次检测版本的时候，如果是同一版本，不再提示，如果有更高版本，会再提示。
                AipSharedPreferences.getInstance(MainActivity.this).setVersion(version);
                dialog.dismiss();
            }
        });
    }
    /**
     * 密码过期处理
     *
     * @param type
     */
    public void showPasswordOutOfDate(int type) {
        HPLog.i(HPLog.TAG_RESULT, "-----showPasswordOutOfDate-------");
        flag_isShow_updatePWD = false;
        DialogInterface.OnClickListener click_gotoupdate = new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                gotoUpdatepassword();
                dialog.dismiss();
            }
        };
        DialogInterface.OnClickListener click_close = new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        };
        if (type == 1) {//即将过期
            showAlertDialog(this, getString(R.string.tip), getString(R.string.tv_password_outof_date_ing), false, getString(R.string.ok), click_gotoupdate, getString(R.string.tv_wating_operation), click_close);
        } else {//已经过期
            showAlertDialog(this, getString(R.string.tip), getString(R.string.tv_password_outof_date_ed), false, click_gotoupdate);
        }
    }

    //去跟新密码--密码过期使用
    public void gotoUpdatepassword() {
        Intent intnet = new Intent(this, ModifyLoginPwdActivity.class);
        intnet.putExtra("forceUpdate", true);
        startActivity(intnet);
    }



    @Override
    public int[] getNoticeAction() {
        int actions[] = {NOTICE_ACTION, VERIFY_UPDATE_ACTION, SWITCH_RECEIVABLES_ACTION, CUSTOM_COMPONENT_ACTION};
        return actions;
    }

    //判断是否显示用户协议 根据商户+标志,isShow返回false表示显示
    private boolean isAgreeMented() {
        boolean isShow = true;
        String key=ClientEngine.KEY_CLIENT_AGREEMENT+AccountUtils.getAccountName(this);
        String agreenmentFlag = String.valueOf(ClientEngine.getInstance().getRMSData(key));
        if (!TextUtils.isEmpty(agreenmentFlag)) {
            try {
                //认为是第一次登入
                if (TextUtils.isEmpty(AccountUtils.getRMSAccountName())) {
                    isShow = false;
                } else {
                    if ("1".equals(agreenmentFlag)) {
                        isShow = true;
                    } else {
                        isShow = false;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                isShow = false;
            }
        } else {
            isShow = false;
        }
        HPLog.i(HPLog.LFP_TAG, "hasShowAgreement:" + isShow);
        return isShow;
    }

    private void showAgreement() {
        currentShowAgreement = true;
        final Dialog dialog = new Dialog(this, R.style.dialog);
        RelativeLayout root_agreement = (RelativeLayout) getLayoutInflater().inflate(R.layout.layout_agreement, null);
        dialog.setContentView(root_agreement);
        WindowManager.LayoutParams p = dialog.getWindow().getAttributes();
        p.width = screenWidth - 120;
        p.height = screenHeight - 300;
        dialog.getWindow().setAttributes(p);
        WebView mWebView = (WebView) root_agreement.findViewById(R.id.wv_agreement);
        CheckBox mCheckBox = (CheckBox) root_agreement.findViewById(R.id.ck_agreement);
        final Button btn_agree = (Button) root_agreement.findViewById(R.id.ok);
        btn_agree.setBackgroundResource(R.drawable.bt_login_enbale);
        mWebView.getSettings().setJavaScriptEnabled(true);
        // 禁用web view 的滚动条，否则右侧会有白边
        mWebView.setHorizontalScrollBarEnabled(true);
        mWebView.setVerticalScrollBarEnabled(true);
        mWebView.requestFocus();
        mWebView.loadUrl(ZZTConfig.HPZZT_URL);
        mCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    btn_agree.setEnabled(true);
                    btn_agree.setBackgroundResource(R.drawable.bt_login_nomal);
                } else {
                    btn_agree.setEnabled(false);
                    btn_agree.setBackgroundResource(R.drawable.bt_login_enbale);
                }
            }
        });
        btn_agree.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (btn_agree.isEnabled()) {
                    dialog.cancel();
                    ClientEngine.getInstance().saveRMSData(ClientEngine.KEY_CLIENT_AGREEMENT+AccountUtils.getAccountName(MainActivity.this),"1");
                    currentShowAgreement=false;
                }
            }
        });
        dialog.setCanceledOnTouchOutside(false);
        dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                currentShowAgreement = false;
            }
        });
        dialog.setCancelable(false);
        dialog.show();
    }
}
